/* -*- c++ -*- */
/*
 * Copyright 2004,2010 Free Software Foundation, Inc.
 *
 * This file is part of GNU Radio
 *
 * GNU Radio is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 *
 * GNU Radio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with GNU Radio; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street,
 * Boston, MA 02110-1301, USA.
 */

/*
 * config.h is generated by configure.  It contains the results
 * of probing for features, options etc.  It should be the first
 * file included in your .cc file.
 */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <howto_spectrum_sensing_cf.h>
#include <gr_io_signature.h>
#include <math.h>
#include <stdio.h>

/*
 * Create a new instance of howto_square_ff and return
 * a boost shared_ptr.  This is effectively the public constructor.
 */
howto_spectrum_sensing_cf_sptr howto_make_spectrum_sensing_cf(int sample_rate, int ninput_samples, int nsub_bands, float pfd, float pfa, float Tcme)
{
  return gnuradio::get_initial_sptr(new howto_spectrum_sensing_cf (sample_rate, ninput_samples, nsub_bands, pfd, pfa, Tcme));
}

/*
 * Specify constraints on number of input and output streams.
 * This info is used to construct the input and output signatures
 * (2nd & 3rd args to gr_block's constructor).  The input and
 * output signatures are used by the runtime system to
 * check that a valid number and type of inputs and outputs
 * are connected to this block.  In this case, we accept
 * only 1 input and 1 output.
 */
static const int MIN_IN = 1;	// mininum number of input streams
static const int MAX_IN = 1;	// maximum number of input streams
static const int MIN_OUT = 1;	// minimum number of output streams
static const int MAX_OUT = 1;	// maximum number of output streams

/*
 * The private constructor
 */
howto_spectrum_sensing_cf::howto_spectrum_sensing_cf (int sample_rate, int ninput_samples, int nsub_bands, float pfd, float pfa, float Tcme)
  : gr_sync_block ("spectrum_sensing_cf",
	      gr_make_io_signature (MIN_IN, MAX_IN, ninput_samples*sizeof (gr_complex)),
	      gr_make_io_signature (MIN_OUT, MAX_OUT, sizeof (float))),
	      d_sample_rate(sample_rate),
	      d_ninput_samples(ninput_samples),
 	      d_nsub_bands(nsub_bands),
	      d_pfd(pfd),
  	      d_pfa(pfa),
 	      d_tcme(Tcme)
{
	segment = new float[d_ninput_samples];
	sorted_segment = new float[d_ninput_samples];
}

/*
 * Our virtual destructor.
 */
howto_spectrum_sensing_cf::~howto_spectrum_sensing_cf ()
{
	delete[] segment;
	delete[] sorted_segment;
}

int
howto_spectrum_sensing_cf::work (int noutput_items,
			       gr_vector_const_void_star &input_items,
			       gr_vector_void_star &output_items)
{
  const gr_complex *in = (const gr_complex *) input_items[0];
  float *out = (float *) output_items[0];

  printf("Number of output items:%d\n",noutput_items);
  for(int k=0;k<noutput_items;k++) {
	printf("Sample rate:%d\n",d_sample_rate);
	printf("Number of samples:%d\n",d_ninput_samples);
	printf("Number of subbands:%d\n",d_nsub_bands);
	printf("Pfd:%f\n",d_pfd);
	printf("Pfa:%f\n",d_pfa);
	printf("These are the samples we have in vector #%d:\n",k);
	for(int i=0;i<d_ninput_samples;i++) {
		printf("%f+j%f\n",in[k*d_ninput_samples + i].real(),in[k*d_ninput_samples + i].imag());
	}
	printf("\n\n\n");

	out[k] = ((float)k+1.0);
  }

  // Tell runtime system how many output items we produced.
  return noutput_items;
	
	/*--------------------------------
    for j=1:1:NIFFT/detection_window_size
	trials_counter = trials_counter + 1;
	ratio = segmented_pdp_copy(j)/Zref;
	if(ratio > alpha)
	false_alarm_counter = false_alarm_counter + 1;
	else
	correct_rejection_counter = correct_rejection_counter + 1;
	end
    end
    false_alarm_rate = false_alarm_counter/trials_counter;
    correct_rejection_rate = correct_rejection_counter/trials_counter;
	--------------------------------*/
}

// Segment the spectrum into blocks with the sum of the energies.
bool howto_spectrum_sensing_cf::segment_spectrum(const gr_complex *in, int input_item_number) {
	
	// d_nsub_bands must be a multiple of d_ninput_samples.
	assert(d_ninput_samples%d_nsub_bands == 0);
	
	int samples_per_band = d_ninput_samples/d_nsub_bands;
	
	for(int k=0;k<d_nsub_bands;k++) {
		segment[k] = 0.0;
		for(int i=0;i<samples_per_band;i++){
			segment[k] = segment[k] + pow(abs(in[input_item_number*d_ninput_samples + k*samples_per_band + i]),2);
		}
		sorted_segment[k] = segment[k];
	}
	return true;
}

//This is the implemenatation of the algorithm proposed in reference [4].
//TODO: The bubble sort algorithm is adopted here however as it's well known this algorihtm is too slow, so pls, rewrite this method with a faster algorithm.
bool howto_spectrum_sensing_cf::sort_energy() {
	float temp;

	//Sort Segmented Power Ddelay Profile vector in increasing order of energy.
	for(int i=0;i<d_nsub_bands;i++) {
		for(int k=0;k<(d_nsub_bands-1);k++) {
			if(sorted_segment[k] > sorted_segment[k+1]) {
				temp = sorted_segment[k+1];
				sorted_segment[k+1] = sorted_segment[k];
				sorted_segment[k] = temp;
			}
		}
	}
	
	return true;
}

// Algorithm used to discard samples. Indeed, it is used to find a speration between noisy samples and signal+noise samples.
float howto_spectrum_sensing_cf::calculate_noise_reference() {
	
	float limiar, energy[d_nsub_bands], zref;
	
	for(I=20;I<d_nsub_bands;I++) {
		limiar = d_tcme/I;
		energy[I] = 0.0;
		for(k=0;k<I;k++) {
			energy[I] = energy[I] + sorted_segment[k];
		}
		if(sorted_segment[I] > limiar*energy[I]) {
			break;
		}
	}
	
	// Return the noise reference.
	return energy[I];
}

bool howto_spectrum_sensing_cf::calculate_scale_factor() {
/*
    % Calculate the scale factor.
    alpha = finv(1-Pfa,(2*detection_window_size),(2*I*detection_window_size))/I;
*/
}

/*
REFERENCES: 

[1] Sesia, S., Baker, M., Toufik, I. - "LTE, the UMTS long term evolution: From theory to practice. Chichester", Wiley InterScience, 2009.
[2] 3GPP Technical Specification 36.213 - "Physical layer procedures (Release 10)", ww.3gpp.org.
[3] Jing Jiang, Muharemovic, Pierre Bertrand - "Random Access Preamble Detection for Long Term Evolution Wireless Networks", Patent number US 2009/0040918 A1.
[4] Fabbryccio A. C. Cardoso, Juliano João Bazzo, and Fabrício Lira Figueiredo, “Método de detecção de sinal primário para faixa de TV”, Caderno CPqD de Tecnologia.

*/

